package com;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 编写一个自旋锁
 */
public class ZiXuan {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    /**
     * 给目标上锁
     */
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "进来了");
        while(!atomicReference.compareAndSet(null,thread)){
            System.out.println(Thread.currentThread().getName() + "在等待解锁");
        }
    }
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "解锁成功");
        atomicReference.compareAndSet(thread,null);
    }

    public static void main(String[] args) throws InterruptedException {
        ZiXuan ziXuan = new ZiXuan();
        new Thread(()->{
            ziXuan.myLock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ziXuan.myUnLock();
        },"Aa").start();
        Thread.sleep(1000);
        new Thread(()->{
            ziXuan.myLock();
            ziXuan.myUnLock();
        },"Bb").start();

    }
}

